/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package core.controller;

import core.api.APIConstant;
import core.api.APIRequest;
import core.definition.GlobalConstant;
import core.definition.MessageCommand;
import core.definition.SystemSubCommand;
import core.factory.SystemMessageFactory;
import core.io.Attribute;
import core.io.Message;
import core.io.Session;
import core.io.SessionAttribute;
import core.log.Monitor;
import core.model.UserInfor;
import java.io.IOException;
import org.apache.mina.core.service.IoHandler;
import org.apache.mina.core.session.IdleStatus;
import org.apache.mina.core.session.IoSession;

/**
 *
 * @author Dung Pham
 */
public class MessageController implements IoHandler {

    public MessageController() {
    }

    @Override
    public void sessionCreated(IoSession iSession) throws Exception {
        iSession.setAttribute(Attribute.CREATE_SESSION_TIME, System.currentTimeMillis());
        //log lại cái này
    }

    @Override
    public void sessionOpened(IoSession iSession) throws Exception {
        //chua biet lam gi
    }

    @Override
    public void sessionClosed(IoSession iSession) throws Exception {
        try {
            if (iSession.containsAttribute(Attribute.SESSION_INFOR)) {
                SessionAttribute sessionInfor = (SessionAttribute) iSession.getAttribute(Attribute.SESSION_INFOR);
                //do logout, update user data
            }
        } catch (Exception ex) {
        }
        iSession.removeAttribute(Attribute.SESSION_INFOR);
    }

    @Override
    public void sessionIdle(IoSession iSession, IdleStatus status) throws Exception {
        if (status.equals(IdleStatus.READER_IDLE)) {
            iSession.close(true);
        }
    }

    @Override
    public void exceptionCaught(IoSession iSession, Throwable exception) throws Exception {
        if (exception instanceof IOException) {  //lỗi io thì close session
            iSession.close(true);
        } else {
            //lỗi khác thì la làng
        }
    }

    @Override
    public void messageReceived(IoSession iSession, Object data) throws Exception {
        if (!iSession.isConnected()) {
            return;
        }
        Message message = (Message) data;
        SessionAttribute sessionInfor = (SessionAttribute) iSession.getAttribute(Attribute.SESSION_INFOR);
        if (sessionInfor == null) {
            sessionInfor = new SessionAttribute();
            Session iwinSession = new Session(iSession, sessionInfor);
            sessionInfor.setIoSession(iwinSession);
        }
        Session session = sessionInfor.getIoSession();
        message.setSession(session);
        proccessMessage(session, message);
    }

    @Override
    public void messageSent(IoSession iSession, Object o) throws Exception {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    /**
     * xử lý message
     *
     * @param sesion
     * @param mesage
     */
    public void proccessMessage(Session session, Message message) {
        Message msg = null;
        switch (message.command) {
            case MessageCommand.SYSTEM_COMMAND:
                proccessSystemMessage(session, message);
                break;
            default:
        }

    }

    private void proccessSystemMessage(Session session, Message message) {
        Message msg = null;
        try {
            int subCommand = message.dis.readInt();
            switch (subCommand) {
                case SystemSubCommand.SYS_CLIENT_INFOR:
                    String client = message.dis.readUTF();
                    //GlobalConstant.GSON.fromJson(client, null)
                    break;
                case SystemSubCommand.SYS_LOGIN:
                    processLogin(session, message);
                    break;
                case SystemSubCommand.SYS_REGISTER:
                    break;
                default:
            }
        } catch (Exception ex) {
        }
    }

    private void processLogin(Session session, Message message) {
        Message msg = null;
        try {
            String username = message.dis.readUTF();
            String password = message.dis.readUTF();
            UserInfor infor = APIRequest.doLoginAPI(username, password);
            //if (infor.getCode() == APIConstant.)
            //msg = SystemMessageFactory.getMessageLogin(result);
            session.sendMessage(msg);
        } catch (Exception ex) {
            Monitor.error("proccess", ex);
        }
    }

    /**
     *
     * @param username
     * @param password
     * @return
     */
    private int doLogin(String username, String password) {
        int result = GlobalConstant.LOGIN_FAIL_WRONG;
        try {
            if (password == null || password.isEmpty()) {
                result = GlobalConstant.LOGIN_FAIL_PASSNULL;
            }            
            //API authen
            if ("test".equals(username) && "t".equals(password)) {
                result = GlobalConstant.LOGIN_SUCCESS;
            }
            //API
            //inner authen
            if (result == GlobalConstant.LOGIN_SUCCESS){
                
            }
        } catch (Exception ex) {
            result = GlobalConstant.LOGIN_FAIL_WRONG;
        } finally {
            return result;
        }
    }
}
